package com.yue92.datalife.service.impl;

import com.yue92.datalife.model.Record;
import com.yue92.datalife.repository.RecordRepository;
import com.yue92.datalife.service.AbstractDbService;
import com.yue92.datalife.service.IRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Service
public class RecordServiceImpl extends AbstractDbService<Record, Long> implements IRecordService {

    @Autowired
    private RecordRepository recordRepository;

    @Override
    public List<Record> findByUserId(Long userId) {
        Sort sort = Sort.by(Sort.Direction.ASC, "sort").and(Sort.by(Sort.Direction.ASC, "id"));
        return recordRepository.findByUserIdAndDisplay(userId, true, sort);
    }

    @Override
    public LocalDate getLocalDate(String recordDate, Integer offset, ChronoUnit chronoUnit) {
        LocalDate date;
        if (StringUtils.isEmpty(recordDate)) {
            date = LocalDate.now();
        } else {
            date = LocalDate.parse(recordDate);
        }

        if (offset != null) {
            date = date.plus(offset, chronoUnit);
        }

        return date;
    }

    @Override
    public JpaRepository<Record, Long> getRepository() {
        return recordRepository;
    }

    @Override
    protected Class<Record> getModelClass() {
        return Record.class;
    }
}
